<template>
  <div>
    <div>
      <!--      <div style="width: 14%;height: 400px;float:left;">-->
      <!--        <el-card class="box-card" style="width: 100%;height: 400px;">-->
      <!--          <div slot="header" class="clearfix">-->
      <!--            <span>在线车辆</span><br>-->
      <!--            <el-button type="text" @click="closeCar()">关闭当前展示</el-button><br>-->
      <!--            <el-button type="text" @click="zsy()">地图自适应</el-button>-->
      <!--          </div>-->
      <!--          <div>-->
      <!--            <li v-for="(item,index) in onlonecar" :key="index" @click="createSocket(item)" :disabled="true">{{item}}</li>-->
      <!--          </div>-->
      <!--        </el-card>-->
      <!--      </div>-->
      <div style="width: 33%;height: 400px;float:left;border:solid #1e90ff 1px">
        <div style="text-align: center;color: #1e90ff;margin-left: -10px;"><h3>实时定位</h3></div>
        <div id="container"></div>
        <el-button type="primary" @click="fetchList(electronicId)">获取</el-button>
      </div>
      <!-- 速度表盘 -->
      <div style="width: 33%;height: 400px;float:left;border:solid #1e90ff 1px;">
        <div class="wrap-container sn-container">
          <div class="sn-content" style="margin-left: -10px;">
            <div style="text-align: center;color: #1e90ff;margin-left: -10px;"><h1>仪表盘</h1></div>
            <div style="margin-top: -20px;">
              <div class="wrap-container">
                <div class="chartsdom" id='chart-gauge'></div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- 另一个表 -->
      <div style="width: 33%;height: 400px;float:left;margin-left: 10px;border:solid #1e90ff 1px">
        <div style="text-align: center;color: #1e90ff;"><h1>电池剩余电量</h1></div>
        <div id="remainingBattery" style="width: 100%;height: 400px;margin-top: -30px;margin-left: 10px;"></div>
      </div>
      <div>
        <el-card style="width: 200px;float: left;margin-left: 12px;margin-top: 20px;">
          <div slot="header" class="clearfix">
            <span>里程</span>
          </div>
          <div>
            {{realTimeCar.mileage==null?"0":realTimeCar.mileage}}
          </div>
        </el-card>
        <el-card style="width: 200px;float: left;margin-left: 12px;margin-top: 20px;">
          <div slot="header" class="clearfix">
            <span>总电压</span>
          </div>
          <div>
            {{realTimeCar.voltage==null?"0":realTimeCar.voltage}}
          </div>
        </el-card>
        <el-card style="width: 200px;float: left;margin-left: 12px;margin-top: 20px;">
          <div slot="header" class="clearfix">
            <span>总电流</span>
          </div>
          <div>
            {{realTimeCar.current==null?"0":realTimeCar.current}}
          </div>
        </el-card>
        <el-card style="width: 200px;float: left;margin-left: 12px;margin-top: 20px;">
          <div slot="header" class="clearfix">
            <span>档位</span>
          </div>
          <div>
            {{realTimeCar.gear==null?"0":realTimeCar.gear}}
          </div>
        </el-card>
        <el-card style="width: 200px;float: left;margin-left: 12px;margin-top: 20px;">
          <div slot="header" class="clearfix">
            <span>燃料消耗率</span>
          </div>
          <div>
            {{realTimeCar.fuelConsumptionRate==null?"0":realTimeCar.fuelConsumptionRate}}
          </div>
        </el-card>
        <el-card style="width: 200px;float: left;margin-left: 12px;margin-top: 20px;">
          <div slot="header" class="clearfix">
            <span>电机控制器温度</span>
          </div>
          <div>
            {{realTimeCar.motorControllerTemperature==null?"0":realTimeCar.motorControllerTemperature}}
          </div>
        </el-card>
        <el-card style="width: 200px;float: left;margin-left: 12px;margin-top: 20px;">
          <div slot="header" class="clearfix">
            <span>电机转速</span>
          </div>
          <div>
            {{realTimeCar.motorSpeed==null?"0":realTimeCar.motorSpeed}}
          </div>
        </el-card>
        <el-card style="width: 200px;float: left;margin-left: 12px;margin-top: 20px;">
          <div slot="header" class="clearfix">
            <span>电机转矩</span>
          </div>
          <div>
            {{realTimeCar.motorTorque==null?"0":realTimeCar.motorTorque}}
          </div>
        </el-card>
        <el-card style="width: 200px;float: left;margin-left: 12px;margin-top: 20px;">
          <div slot="header" class="clearfix">
            <span>电机温度</span>
          </div>
          <div>
            {{realTimeCar.motorTemperature==null?"0":realTimeCar.motorTemperature}}
          </div>
        </el-card>
        <el-card style="width: 200px;float: left;margin-left: 12px;margin-top: 20px;">
          <div slot="header" class="clearfix">
            <span>电机电压</span>
          </div>
          <div>
            {{realTimeCar.motorVoltage==null?"0":realTimeCar.motorVoltage}}
          </div>
        </el-card>
        <el-card style="width: 200px;float: left;margin-left: 12px;margin-top: 20px;">
          <div slot="header" class="clearfix">
            <span>电机电流</span>
          </div>
          <div>
            {{realTimeCar.motorCurrent==null?"0":realTimeCar.motorCurrent}}
          </div>
        </el-card>
        <el-card style="width: 200px;float: left;margin-left: 12px;margin-top: 20px;">
          <div slot="header" class="clearfix">
            <span>车辆状态</span>
          </div>
          <div>
            {{realTimeCar.vehicleStatus==1||realTimeCar.vehicleStatus==null?"正常":"异常"}}
          </div>
        </el-card>
        <el-card style="width: 200px;float: left;margin-left: 12px;margin-top: 20px;">
          <div slot="header" class="clearfix">
            <span>EAS(防盗系统)状态</span>
          </div>
          <div>
            {{realTimeCar.easStatus==1||realTimeCar.easStatus==null?"正常":"异常"}}
          </div>
        </el-card>
        <el-card style="width: 200px;float: left;margin-left: 12px;margin-top: 20px;">
          <div slot="header" class="clearfix">
            <span>ABS(防抱死)状态</span>
          </div>
          <div>
            {{realTimeCar.absStatus==1||realTimeCar.absStatus==null?"正常":"异常"}}
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>
<script src='echarts.js'></script>
<script src='echarts-liquidfill.js'></script>
<script>

// import AMapLoader from '@amap/amap-jsapi-loader';
// import {findAllOnlineCar} from '@/api/dispose/dispose';
import {getFence} from "@/api/system/fence";


export default {
  name:"screen",
  data() {
    return {
      show:[],
      tableData:[],
      isshow:true,
      // 链接
      linkCount:1,
      // 定时器
      interval:null,
      // 倒计时
      countdown:10,
      // 当前车辆
      realTimeCar:{},
      //在线车辆
      onlonecar:[],

      // 速度
      option: null,
      timer: null,
      myChart:null,

      // 电池
      option1: null,
      myChart1:null,
      electronicId :null,


      map:null,
      // websocket
      ws:null,
      ws_url:'ws://localhost:8080/websocket/screen/',
      vin: null,
      // vin:Math.ceil(Math.random()*10000000),
    }
  },

  created: function() {
    window.onLoad = function() {
      //所有关于地图的逻辑全部都在这个回调里面，
      // 保证高德地图加载完毕
      let mapGaoDe;
      mapGaoDe = new AMap.Map("container", {
        center: [116.397428, 39.90923],
        zoom: 10,
        viewMode: '3D',
        resizeEnable: true,
      });

      // 缩放地图到合适的视野级别
      mapGaoDe.setFitView()
    };
    // 加载高德地图库
    var webapi = document.createElement("script");
    webapi.src = `https://webapi.amap.com/maps?v=2.0&key=2133ec955e1135c305be7c1c729497ba&plugin=AMap.PolygonEditor&callback=onLoad`;
    // 将api文件引入到页面中，加载完毕以后就会回调函数 onLoad
    document.head.appendChild(webapi);
    var jsapi_demos = document.createElement("script");
    jsapi_demos.src = `https://a.amap.com/jsapi_demos/static/demo-center/js/demoutils.js`;
    document.head.appendChild(jsapi_demos);
  },

  methods: {
    closeCar(){
      this.isshow=true;
      this.countdown=10;
      this.linkCount=1;
      this.close_ws();
      this.realTimeCar={};
      this.option1.xAxis.data=[];
      this.option1.series[0].data=[];
      this.myChart1.setOption(this.option1, true)
      clearInterval(this.interval);
    },
    getshow() {
      var electronicId = this.tableData;
      if (electronicId != null) {
        this.arr1 = JSON.parse(electronicId);
        var show = [];
        for (let i = 0; i < this.arr1.length; i++) {
          this.arr2 = JSON.parse(this.arr1[i]);
          for (let j = 0; j < this.arr2.length; j++) {
            show.push({
              lat: parseFloat(this.arr2[j].lat),
              lng: parseFloat(this.arr2[j].lng)
            });
          }
        }
        // 在这里进行其他操作
        this.init(show); // 将新数组传递给 init 方法
      }
    },


    fetchList(electronicId) {
      const self = this;
      fetch(`http://127.0.0.1:9201/fence/${electronicId}`)
        .then(response => response.json())
        .then(resp => {
          self.tableData = resp.data.violationSpecific;
          self.getshow();
        })
        .catch(error => {
          console.error('获取列表失败', error);
        });
    },




    init(show) {
      var map = new AMap.Map('container', {
        center: [116.397428, 39.90923],
        zoom: 11,
        viewMode: '3D',
        resizeEnable: true,
        // 在这里配置地图的初始化参数
      });
      var path4 = [];
      for (let i = 0; i < show.length; i++) {
        path4.push(new AMap.LngLat(show[i].lng, show[i].lat));
      }
      console.log("==================");
      console.log(path4);
      this.showpolygon(map, path4); // 传递地图对象给 showpolygon 方法
    },

    showMarkers(map, data) {
      // 当前展示的标记列表
      var markers = [];

      // 根据索引范围显示对应的标记
      function showMarkers() {
        // 获取当前索引范围内的坐标点
        var currentCoords = data.slice(0, markers.length + 1);

        // 如果超过了坐标总数，则停止添加新的标记
        if (currentCoords.length > data.length) {
          clearInterval(intervalId);
          return;
        }

        // 清除之前的标记
        markers.forEach(function(marker) {
          map.remove(marker);
        });

        // 清空标记列表
        markers = [];

        // 遍历坐标点并创建新的标记并添加到地图上
        currentCoords.forEach(function(coord) {
          var marker = new AMap.Marker({
            position: coord,
            map: map
          });
          markers.push(marker);
        });
      }

      // 初始展示一个标记
      showMarkers();

      // 每隔2秒切换展示下一个标记并移除最早的一个标记
      var intervalId = setInterval(showMarkers, 2000);
    },

    showpolygon(map, path3) {
      let polygon = new AMap.Polygon({
        path: path3,
        map: map,
        strokeColor: '#CA433A',
        fillColor: '#43CA3A',
        fillOpacity: 0.1
      });

      // 坐标数据
      var data = [
        [116.316376, 39.964491],
        [116.466751, 39.966596],
        [116.480484, 39.909736],
        [116.450484, 39.909736],
        [116.435852, 39.824358],
        [116.285477, 39.860209],
        [116.261444, 39.93238]
      ];
      // 展示标记
      this.showMarkers(map, data);
    }
//  当前展示的标记列表和索引
//       var markers = [];
//       var currentIndex = 0;
//
// // 添加一个新的标记并移除最早的一个标记
//       function addMarker() {
//         if (markers.length === 3) {
//           var firstMarker = markers.shift();
//           map.remove(firstMarker);
//         }
//
//         var coord = data[currentIndex++];
//         var marker = new AMap.Marker({
//           position: coord,
//           map: map
//         });
//         markers.push(marker);
//
//         if (currentIndex >= data.length) {
//           clearInterval(intervalId);
//         }
//       }
//
// // 初始展示第一个标记
//       addMarker();
//
// // 每隔2秒添加一个新的标记并移除最早的一个标记
//       var intervalId = setInterval(addMarker, 2000);
    },

    createSocket(vin){
      this.isshow=false;
      this.vin=vin;
      this.createWebSocket();
      this.interval=setInterval(()=>{
        if(this.countdown<=0){
          if(this.linkCount<=5){
            this.countdown=10;
            this.$message.error("尝试第"+this.linkCount+"次链接")
            this.linkCount++;
            this.createWebSocket();
          }else{
            console.log("链接失败,请检查车辆"+this.vin+"是否上线");
            this.$message.error("链接失败,请检查该车辆"+this.vin+"是否上线");
            this.closeCar();
          }
        }else{
          this.countdown=this.countdown-1;
        }
      },1000)
    },
    // 获取在线车辆
    getAllOnlineCar(){
      findAllOnlineCar().then(res=>{
        this.onlonecar=res;
      })
    },
    // 电池表
    getEchart1() {
      this.myChart1 = this.$echarts.init(document.getElementById('remainingBattery'))
      this.option1 = {
        xAxis: {
          type: 'category',
          data: []
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data: [],
            type: 'bar'
          }
        ]
      };
      this.myChart1.setOption(this.option1, true);

      window.addEventListener('resize', () => {
        this.myChart1.resize();
      });
    },
    // 速度仪表盘
    getEchart() {
      this.myChart = this.$echarts.init(document.getElementById('chart-gauge'))
      this.option = {
        tooltip: {
          formatter: '{a} <br/>{c} {b}'
        },
        series: [{
          name: '速度',
          type: 'gauge',
          min: 0,
          max: 220,
          splitNumber: 11,
          // radius: '50%',
          axisLine: { // 坐标轴线
            lineStyle: { // 属性lineStyle控制线条样式
              color: [
                [0.09, 'lime'],
                [0.82, '#1e90ff'],
                [1, '#ff4500']
              ],
              width: 3,
              // shadowColor: '#fff', //默认透明
              // shadowBlur: 10
            }
          },
          axisLabel: { // 坐标轴小标记
            fontWeight: 'bolder',
            color: '#1e90ff',
            shadowColor: '#1e90ff', //默认透明
            // shadowBlur: 10
          },
          axisTick: { // 坐标轴小标记
            length: 15, // 属性length控制线长
            lineStyle: { // 属性lineStyle控制线条样式
              color: 'auto',
              // shadowColor: '#fff', //默认透明
              // shadowBlur: 10
            }
          },
          splitLine: { // 分隔线
            length: 25, // 属性length控制线长
            lineStyle: { // 属性lineStyle（详见lineStyle）控制线条样式
              width: 3,
              color: '#1e90ff',
              // shadowColor: '#fff', //默认透明
              // shadowBlur: 10
            }
          },
          pointer: { // 分隔线
            // shadowColor: '#fff', //默认透明
            // shadowBlur: 5
          },
          title: {
            textStyle: { // 其余属性默认使用全局文本样式，详见TEXTSTYLE
              fontWeight: 'bolder',
              fontSize: 20,
              fontStyle: 'italic',
              color: '#1e90ff',
              shadowColor: '#1e90ff', //默认透明
              // shadowBlur: 10
            }
          },
          detail: {
            // backgroundColor: 'rgba(30,144,255,0.8)',
            // borderWidth: 1,
            // borderColor: '#fff',
            // shadowColor: '#fff', //默认透明
            // shadowBlur: 5,
            offsetCenter: [0, '50%'], // x, y，单位px
            textStyle: { // 其余属性默认使用全局文本样式，详见TEXTSTYLE
              fontWeight: 'bolder',
              fontSize: 25,
              color: '#1e90ff'
            }
          },
          data: [{
            value: 0,
            name: 'km/h'
          }]
        }]
      }
      this.myChart.setOption(this.option, true);
      window.addEventListener('resize', () => {
        this.myChart.resize();
      });
    },
    // websocket
    createWebSocket(){
      //debugger
      this.ws = new WebSocket(this.ws_url + this.vin);
      //ws = new WebSocket("ws://10.2.33.14:8080/websocket");
      // 建立 web socket 连接成功触发事件
      this.ws.onopen = this.onopen;
      // 接收服务端数据时触发事件
      this.ws.onmessage = this.onmessage;
      // 断开 web socket 连接成功触发事件
      this.ws.onclose = this.onclose;

      this.ws.onerror = this.onerror;
    },
    sendMessage() {
      if (this.message != '') {
        this.ws.send(this.message);
        this.message ='';
      }
    },
    onopen() {
      this.log_message('Info: WebSocket 连接成功.');
    },
    onmessage (evt) {
      this.countdown=10;
      this.linkCount=1;
      var received_msg = evt.data;
      let jsonMag=JSON.parse(received_msg);

      this.realTimeCar=jsonMag;

      let vin=jsonMag['vin'];
      let lon=jsonMag['longitude'];
      let lat=jsonMag['latitude'];
      let speed=jsonMag['speed'];
      let remainingBattery=jsonMag['remainingBattery'];
      console.log(vin);
      this.addMarker(vin,lon,lat);


      this.option.series[0].data[0].value = Number(speed).toFixed(2);
      this.option1.xAxis.data.push("");
      this.option1.series[0].data.push(remainingBattery);
      this.myChart1.setOption(this.option1, true)
      this.myChart.setOption(this.option, true)
    },
    onclose () {
      this.log_message('Info: WebSocket 关闭.');
    },
    onerror () {
      this.log_message('Info: WebSocket 出现错误.');
    },
    log_message(msg){

    },
    close_ws(){
      this.ws.close();
    },
    zsy(){
      this.map.setFitView(null, false, [300, 200, 300, 200]);
    },
    addMarker(vin,log,lat) {
      let marker = new AMap.Marker({
        icon: "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
        position: [log,lat],
      });
      marker.setLabel({
        direction:'right',
        offset: new AMap.Pixel(10,10),  //设置文本标注偏移量
        content: "<div class='info'>"+vin+"</div>",
      })
      marker.setMap(this.map);
      setTimeout(() => {
        marker.setMap(null);
        marker=null;
      },1000);
    },
    initMap(){
      AMapLoader.load({
        "key": "7a372adc25a756e8aeca5687e0f7f0e2",              // 申请好的Web端开发者Key，首次调用 load 时必填
        "version": "2.0",   // 指定要加载的 JS API 的版本，缺省时默认为 1.4.15
        "plugins": [],           // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      }).then((AMap)=>{
        this.map = new AMap.Map('container');
      }).catch(e => {
        console.log(e);
      })
  },
  mounted() {
    // 获取路由参数 electronicId 的值
    const electronicId = this.$route.query.electronicId;
    this.electronicId =electronicId

    this.$nextTick(()=>{
      this.initMap();
    })
    this.getEchart();
    this.getEchart1();
    this.getAllOnlineCar();
  },
  destroyed(){
    this.closeCar();
    this.close_ws();
  },

}
</script>
<style>
#container {
  width: 100%;
  height: 300px;
}
.sn-title{
  text-align: center;
  color: white;
}
.wrap-container{
  width: 432px;
  height: 400px;}
.chartsdom{
  width: 100%;
  height: 100%;
}
.info{
  font-size: 20px;
  position: relative;
  margin:0;
  top: 0;
  right: 0;
  min-width: 0;
}
</style>
